package com.sdk.util;

import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogUtils {
    private static String commonTag = "SdkDemo";
    private static String mLogFile = "/sdcard/sdkdemo.log";
    private   static boolean mIsWriteLog = false;
    private static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);//日期格式;


    public static void setLogToFile(boolean isWriteLog){
        mIsWriteLog = isWriteLog;
    }

    public static boolean getLogToFile(){
        return mIsWriteLog;
    }


    public static void d(final String Tag, final Object content){
        String msg = content.toString();
        int strLength = msg.length();
        int start = 0;
        int end = 3000;
        for (int i = 0; i < 100; i++) {
            if (strLength > end) {
                Log.d(commonTag + ":" + Tag, msg.substring(start, end));
                start = end;
                end = end + 3000;
            } else {
                Log.d(commonTag + " : " + Tag, msg.substring(start, strLength));
                break;
            }
        }
        if(mIsWriteLog){
            try {
                File file = new File(mLogFile);
                String logStr  = mDateFormat.format(new Date()) + " " + Tag + " " + msg + "\n";//log日志内容，可以自行定制
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法，不用关闭
                BufferedWriter bw = null;
                try {
                    fos = new FileOutputStream(mLogFile, true);//这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
                    bw = new BufferedWriter(new OutputStreamWriter(fos));
                    bw.write(logStr);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }  finally {
                    try {
                        if (bw != null) {
                            bw.close();//关闭缓冲流
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void w(String Tag, Object content){
        Log.e(commonTag + Tag, content.toString());
    }

    public static void e(String Tag, Object content){
        Log.e(commonTag + Tag, content.toString());
    }
}
